package cn.shyouchi.wuguanjia.android.ui.completeinfo;

import android.Manifest;
import android.app.Activity;
import android.app.DialogFragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.jeanboy.cropview.cropper.CropperHandler;
import com.jeanboy.cropview.cropper.CropperManager;
import com.jeanboy.cropview.cropper.CropperParams;

import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.shyouchi.wuguanjia.android.R;
import cn.shyouchi.wuguanjia.android.base.BaseActivity;
import cn.shyouchi.wuguanjia.android.model.User;
import cn.shyouchi.wuguanjia.android.widget.dialog.ConfirmIdInfoDialogFragment;
import cn.shyouchi.wuguanjia.android.utils.LogUtil;
import cn.shyouchi.wuguanjia.android.widget.TopBar;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;


@RuntimePermissions
public class ImproveBasicInfoActivity extends BaseActivity implements ConfirmIdInfoDialogFragment.ConfirmIdInfoDialogListener,
        BasicInfoContract.View, CropperHandler {
    @BindView(R.id.id_card_positive_image_view)
    ImageView idCardPositiveImageView;
    @BindView(R.id.id_card_negative_image_view)
    ImageView idCardNegativeImageView;
    private static final String TAG = "ImprovePersonalInfo";
    private static final int REQUEST_TAKE_PHOTO = 1;
    private static final int REQUEST_TAKE_PHOTO_OF_ID_CARD_POSITIVE = 2;
    private static final int REQUEST_TAKE_PHOTO_OF_ID_CARD_NEGATIVE = 3;
    @BindView(R.id.take_photo_of_id_card_positive_button)
    Button takePhotoOfIdCardPositiveButton;
    @BindView(R.id.take_photo_of_id_card_negative_button)
    Button takePhotoOfIdCardNegativeButton;
    @BindView(R.id.improve_info_submit_button)
    Button improveInfoSubmitButton;
    private User mUser;
    private int photoType = REQUEST_TAKE_PHOTO_OF_ID_CARD_POSITIVE;
    BasicInfoPresenter mPresenter;

    @BindView(R.id.topBar)
    TopBar topBar;

    private String frontImgPath, reverseImgPath;

    public static void start(Context context, User user) {
        Intent intent = new Intent(context, ImproveBasicInfoActivity.class);
        intent.putExtra("user", user);
        context.startActivity(intent);
    }

    @Override
    public int initContentView() {
        return R.layout.activity_improve_basic_info;
    }

    @Override
    public void initInjector() {
        mUser = getIntent().getParcelableExtra("user");
        if (mUser == null || TextUtils.isEmpty(mUser.getUsername()) || TextUtils.isEmpty(mUser.getPassword())) {
            return;
        }
        mPresenter = new BasicInfoPresenter(this, mUser);
        mPresenter.attachView(this);
    }

    @Override
    public void initUiAndListener() {
        ButterKnife.bind(this);
        topBar.setTitle(getTitle().toString());
        topBar.setLeftIcon(R.mipmap.ic_back);
        setSupportActionBar(topBar.getToolbar());
        CropperManager.getInstance().build(this);
    }

    @Override
    protected boolean isApplyStatusBarTranslucency() {
        return false;
    }

    @Override
    protected boolean isApplyStatusBarColor() {
        return true;
    }


    @Override
    public void showToast(String msg) {
        Toast.makeText(mContext, msg, Toast.LENGTH_LONG).show();
    }

    @Override
    public void verifySuccess(User user) {
        LogUtil.json(user);
        showNoticeDialog(mUser);
    }

    public void showNoticeDialog(User user) {
        ConfirmIdInfoDialogFragment dialog = new ConfirmIdInfoDialogFragment();
        dialog.show(getFragmentManager().beginTransaction(), "NoticeDialogFragment", user);
    }


    @Override
    public Activity getActivity() {
        return this;
    }

    @Override
    public CropperParams getParams() {
        return new CropperParams(856, 540);
    }

    @Override
    public void onCropped(Uri uri) {
        try {
            Bitmap bm = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
            if (photoType == REQUEST_TAKE_PHOTO_OF_ID_CARD_POSITIVE) {
                idCardPositiveImageView.setImageBitmap(bm);
                frontImgPath = uri.getPath();
            } else {
                reverseImgPath = uri.getPath();
                idCardNegativeImageView.setImageBitmap(bm);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onCropCancel() {

    }

    @Override
    public void onCropFailed(String msg) {

    }

    @OnClick(R.id.take_photo_of_id_card_positive_button)
    public void takePositivePic() {
        photoType = REQUEST_TAKE_PHOTO_OF_ID_CARD_POSITIVE;
        ImproveBasicInfoActivityPermissionsDispatcher.pickFromCameraWithCheck(this);
    }

    @OnClick(R.id.take_photo_of_id_card_negative_button)
    public void takeNegativePic() {
        photoType = REQUEST_TAKE_PHOTO_OF_ID_CARD_NEGATIVE;
        ImproveBasicInfoActivityPermissionsDispatcher.pickFromCameraWithCheck(this);
    }

    @OnClick(R.id.improve_info_submit_button)
    public void submit() {
        mPresenter.verifyIDCard(frontImgPath, reverseImgPath);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        CropperManager.getInstance().handlerResult(requestCode, resultCode, data);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        ImproveBasicInfoActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @NeedsPermission({Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    public void pickFromCamera() {
        CropperManager.getInstance().pickFromCamera();
    }

    @NeedsPermission({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    public void pickFromGallery() {
        CropperManager.getInstance().pickFromGallery();
    }

    @OnShowRationale({Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    public void showRationaleForCamera(PermissionRequest request) {
        showRationaleDialog("该操作需要使用摄像头，请允许！", request);
    }

    @OnShowRationale({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    public void showRationaleForPick(PermissionRequest request) {//权限说明
        showRationaleDialog("该操作需要操作内存卡，请允许！", request);
    }

    private void showRationaleDialog(String msg, final PermissionRequest request) {
        new AlertDialog.Builder(getActivity())
                .setPositiveButton("允许", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(@NonNull DialogInterface dialog, int which) {
                        request.proceed();
                    }
                })
                .setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(@NonNull DialogInterface dialog, int which) {
                        request.cancel();
                    }
                })
                .setCancelable(false)
                .setMessage(msg)
                .show();
    }

    @Override
    public void onDialogPositiveClick(DialogFragment dialog) {
        dialog.dismiss();
        ImproveDetailInfoActivity.start(mContext, mUser);
        finish();
    }

    @Override
    public void onDialogNegativeClick(DialogFragment dialog) {

    }
}
